package tr.com.netgis;

import tr.com.netgis.util.Utility;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.text.ClipboardManager;
import android.util.Log;
import android.widget.Toast;

/**
 * 
 * @author NetGis
 * 
 */
public class Preferences extends PreferenceActivity {
	
	public static class PrefSetLocationChangedApi {
		
		private Preferences activity;
		private IMTSServiceApi api;
		private OnSharedPreferenceChangeListener prefListener = new OnSharedPreferenceChangeListener(){
		      public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
		    	  if (SharedPrefs.KEY_LOCATION_SIZE.equals(key) || SharedPrefs.KEY_MIN_DISTANCE.equals(key) || 
		    			  SharedPrefs.KEY_MIN_TIME.equals(key) || SharedPrefs.KEY_SEND_FREQUENCY.equals(key) ||
		    			  SharedPrefs.KEY_USE_GPS.equals(key)) {
		              try {
		            	  api.sendCommand(MTSService.MSG_MINIMUM_DISTANCE_CHANGE_FOR_UPDATES);
		              } catch (RemoteException e) {
		            	  e.printStackTrace();
		            	  Log.e(TAG, e.getMessage(), e);
		              }		    		  
		    	  }
		    	  if (activity != null && activity.hasWindowFocus()) {
		    		  activity.displayValuesInSummary();
		    	  }
		      }
		};
		private ServiceConnection serviceConnection = new ServiceConnection() {
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				Log.i(TAG, "Service connection established");
				api = IMTSServiceApi.Stub.asInterface(service);
			}

			@Override
			public void onServiceDisconnected(ComponentName name) {
				Log.i(TAG, "Service connection closed");
			}
		};
		public OnSharedPreferenceChangeListener getPrefListener() {
			return prefListener;
		}
		public ServiceConnection getServiceConnection() {
			return serviceConnection;
		}
		public void setActivity(Preferences activity) {
			this.activity = activity;
		}
		
	}
	
	
	private static final String TAG = "Preferences";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SharedPrefs.getInstance();
		addPreferencesFromResource(R.xml.preferences);
		setTitle("MTS " + Utility.versionName());
		
		
	    Preference deviceIdPref = (Preference) findPreference( "deviceId" );
	    deviceIdPref.setSummary(Utility.getDeviceId());
	    deviceIdPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			
			@Override
			public boolean onPreferenceClick(Preference preference) {
				ClipboardManager ClipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			    ClipMan.setText(preference.getSummary());
			    Toast.makeText(getApplicationContext(), "Cihaz kimliği kopyalandı", Toast.LENGTH_SHORT).show();			    
				return true;
			}
		});
	    
	    Preference button = (Preference)findPreference("aboutBtn");
	    button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
	    	
            @Override
            public boolean onPreferenceClick(Preference arg0) {
            	showAbout();
                return true;
            }
        });
        
        PreferenceCategory catAuth = (PreferenceCategory) findPreference("categoryAuth");
        catAuth.removePreference(findPreference(SharedPrefs.KEY_PASSWORD));
        //catAuth.removePreference(findPreference(SharedPrefs.KEY_SESSION_ID));
        
        Preference prefUserName = findPreference(SharedPrefs.KEY_USER_NAME);
        prefUserName.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			
			@Override
			public boolean onPreferenceClick(Preference preference) {
				showLogin();
				return true;
			}
		});
        
		/*
	    PrefSetLocationChangedApi changedApi = new PrefSetLocationChangedApi();
        SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        mySharedPreferences.registerOnSharedPreferenceChangeListener(changedApi.getPrefListener());
		bindService(Constants.SET_LOCATION_SERVICE_INTENT, changedApi.getServiceConnection(), 0);
		*/
	}
	
	protected void onResume() {
	    super.onResume();   
        NGApplication.assignPreferencesActivityToChangedApi(this);
        displayValuesInSummary();
	}
	
	@Override     
	protected void onPause() {         
	    super.onPause();          
		NGApplication.assignPreferencesActivityToChangedApi(null);
	}
	

	@Override
	protected void onDestroy() {
		super.onDestroy();
		NGApplication.assignPreferencesActivityToChangedApi(null);
	}
	
	public void displayValuesInSummary (){

		Preference pref = findPreference(SharedPrefs.KEY_MIN_TIME);
		String summ = getResources().getString(R.string.prefSummaryMIN_TIME);
		pref.setSummary(summ + ": " +  SharedPrefs.getInstance().getMinTimeView());
		
		pref = findPreference(SharedPrefs.KEY_MIN_DISTANCE);
		summ = getResources().getString(R.string.prefSummaryMIN_DISTANCE);
		pref.setSummary(summ + ": " +  SharedPrefs.getInstance().getMinDistanceView());
		
		pref = findPreference(SharedPrefs.KEY_SEND_FREQUENCY);
		summ = getResources().getString(R.string.prefSummaryMIN_SEND_FREQUENCY);
		pref.setSummary(summ + ": " +  SharedPrefs.getInstance().getSendFrequencyView());

		pref = findPreference(SharedPrefs.KEY_LOCATION_SIZE);
		summ = getResources().getString(R.string.prefSummaryLOCATION_SIZE);
		pref.setSummary(summ + ": " +  SharedPrefs.getInstance().getLocationSize());

		pref = findPreference(SharedPrefs.KEY_USER_NAME);
		summ = SharedPrefs.getInstance().getUserName();
		pref.setSummary(Utility.isEmpty(summ) ? "Kullanıcı adı boş" : summ );
		
		pref = findPreference(SharedPrefs.KEY_SESSION_ID);
		summ = SharedPrefs.getInstance().getSessionId();
		pref.setSummary(summ);
	}
	
	private void showAbout (){
		Intent intent = new Intent(this, AboutActivity.class);
        startActivity(intent);		
	}
	
	/**
	 * Shows username and password
	 */
	private void showLogin(){
		Intent intent = new Intent(this, LoginActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(LoginActivity.SOURCE_KEY, this.getClass().getSimpleName());
		intent.putExtras(bundle);
        startActivity(intent);		
	}
	
	
}
